package com.tjy.wfx;

import com.tjy.wfx.dao.SysRoleMapper;
import com.tjy.wfx.model.SysRole;
import com.tjy.wfx.model.UserInfo;
import com.tjy.wfx.service.UserInfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class WfxRealm extends AuthorizingRealm {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前用户信息
        UserInfo userInfo  = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        //调用dao方法查询用户对应的角色信息
        List<SysRole> role = sysRoleMapper.findRole(userInfo.getAccount());
        //simpleAuthenticationInfo 存放用户信息
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (SysRole sysRole : role) {
            System.out.println("------进入授权方法------用户角色为:"+sysRole);
            simpleAuthorizationInfo.addRole(sysRole.getRoleName());
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("===================进入认证方法");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        UserInfo userInfo=userInfoService.login(token.getUsername());
        if(userInfo==null){
            return null;
        }
        return new SimpleAuthenticationInfo(userInfo,userInfo.getPassword(), ByteSource.Util.bytes(userInfo.getAccount()),getName());
    }
}
